package com.sogou.adm.bizdev.dataimport.service;

import java.util.ArrayList;
import java.util.List;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.JobDetailBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sogou.adm.bizdev.dataimport.constants.JobDataMapKey;
import com.sogou.adm.bizdev.dataimport.job.DumbJob;
import com.sogou.adm.bizdev.dataimport.vo.DataJobDetail;

@Service
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class JobManager {
	@Autowired
	SchedulerFactoryBean schedulerFactory;

	public List<DataJobDetail> getAll() throws SchedulerException {

		Scheduler scheduler = schedulerFactory.getScheduler();

		List<DataJobDetail> dataJobDetails = new ArrayList<DataJobDetail>();
		String[] jobGroupNames = scheduler.getJobGroupNames();
		for (String jobGroupName : jobGroupNames) {
			String[] jobNames = scheduler.getJobNames(jobGroupName);
			for (String jobName : jobNames) {
				JobDetail jobDetail = scheduler.getJobDetail(jobName, jobGroupName);

				dataJobDetails.add(new DataJobDetail(jobDetail));
			}
		}
		return dataJobDetails;
	}

	public void addJob(DataJobDetail dataJobDetail) throws SchedulerException {
		JobDetailBean jobDetail = new JobDetailBean();
		jobDetail.setJobClass(DumbJob.class);
		jobDetail.setName(dataJobDetail.getName());
		jobDetail.setGroup(dataJobDetail.getGroup());
		jobDetail.getJobDataMap().put(JobDataMapKey.JOB_XML_CONFIG, dataJobDetail.getConfig());
		jobDetail.getJobDataMap().put(JobDataMapKey.JOB_CREATOR, dataJobDetail.getCreator());
		// TODO 判断重复问题
		schedulerFactory.getScheduler().addJob(jobDetail, true);
	}

	public void deleteJob(String jobName, String groupName) throws SchedulerException {
		schedulerFactory.getScheduler().deleteJob(jobName, groupName);
	}

	public DataJobDetail getJob(String jobName, String groupName) throws SchedulerException {
		return new DataJobDetail(schedulerFactory.getScheduler().getJobDetail(jobName, groupName));
	}

}
